package flc.ast.activity;

import static com.stark.imgocr.api.VerifyMethod.APPCODE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.fliter.PhotoProcessing;
import com.stark.imgedit.model.ColorTuneRange;
import com.stark.imgedit.utils.BmpUtil;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;
import com.stark.imgocr.ImgOcrEntry;
import com.stark.imgocr.api.Config;
import com.stark.imgocr.api.IRetCallback;
import com.stark.imgocr.api.bean.OcrRetBean;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.MagnifyFilterAdapter;
import flc.ast.bean.MyPictureFilterBean;
import flc.ast.databinding.ActivityPictureMagnifyBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class PictureMagnifyActivity extends BaseAc<ActivityPictureMagnifyBinding> {

    public static String sImgPath;
    private Bitmap mImgBitmap, mRetBitmap;
    private MagnifyFilterAdapter filterAdapter;
    private int oldPosition;
    private float mBrightness = 1;
    private float mSaturation = 1;
    private float mContrast = 0;
    private Matrix matrix = new Matrix();
    private float minScale = 1.0f; // 最小缩放比例
    private float maxScale = 3.0f; // 最大缩放比例

    @Override
    protected int onCreate() {
        return R.layout.activity_picture_magnify;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPictureMagnifyBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvFilter.setOnClickListener(this);
        mDataBinding.tvRecognize.setOnClickListener(this);
        mDataBinding.tvMagnify.setOnClickListener(this);
        mDataBinding.tvMore.setOnClickListener(this);

        mDataBinding.rvPicFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new MagnifyFilterAdapter();
        mDataBinding.rvPicFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvFilter://滤镜
                clearSelection();
                mDataBinding.llFilter.setVisibility(View.VISIBLE);
                break;
            case R.id.tvRecognize://识别
                applyCropImage(ImageUtils.getBitmap(sImgPath));
                break;
            case R.id.tvMagnify://放大
                clearSelection();
                mDataBinding.llMagnify.setVisibility(View.VISIBLE);
                break;
            case R.id.tvMore://更多
                clearSelection();
                mDataBinding.llMore.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        filterAdapter.getItem(oldPosition).setSelect(false);
        filterAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyItemChanged(position);
        setFilter(position);
    }

    @Override
    protected void initData() {
        mImgBitmap = ImageUtils.getBitmap(sImgPath);
        mRetBitmap = ImageUtils.getBitmap(sImgPath);
        mDataBinding.imageViewTouch.setImageBitmap(mImgBitmap);
//        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
//        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
        //滤镜数据
        String[] mFilters = getResources().getStringArray(R.array.filters);
        List<MyPictureFilterBean> listFilter = new ArrayList<>();
        listFilter.add(new MyPictureFilterBean(mFilters[0], "#00000000", true));
        listFilter.add(new MyPictureFilterBean(mFilters[1], "#323333", false));
        listFilter.add(new MyPictureFilterBean(mFilters[2], "#C376F3", false));
        listFilter.add(new MyPictureFilterBean(mFilters[3], "#6F7171", false));
        listFilter.add(new MyPictureFilterBean(mFilters[4], "#505151", false));
        listFilter.add(new MyPictureFilterBean(mFilters[5], "#999999", false));
        listFilter.add(new MyPictureFilterBean(mFilters[6], "#513232", false));
        listFilter.add(new MyPictureFilterBean(mFilters[7], "#787A7A", false));
        listFilter.add(new MyPictureFilterBean(mFilters[8], "#5000FF00", false));
        listFilter.add(new MyPictureFilterBean(mFilters[9], "#500000FF", false));
        listFilter.add(new MyPictureFilterBean(mFilters[10], "#50FF0000", false));
        listFilter.add(new MyPictureFilterBean(mFilters[11], "#50FFFF00", false));
        filterAdapter.setList(listFilter);

        mDataBinding.sbMagnify.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 计算当前缩放比例（进度0~200对应1x~3x）
                float scale = minScale + (maxScale - minScale) * (progress / 200f);

                // 重置Matrix并应用缩放
                matrix.reset();
                matrix.postScale(scale, scale, mDataBinding.imageViewTouch.getWidth()/2f, mDataBinding.imageViewTouch.getHeight()/2f); // 以图片中心为缩放点
                mDataBinding.imageViewTouch.setImageMatrix(matrix);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //brightness
        mDataBinding.sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mBrightness = calSeekBarRealValue(mDataBinding.sbBrightness, progress, ColorTuneRange.BRIGHTNESS);
                //0-2
                updateImageViewBitmap();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //设置滤镜
    private void setFilter(final int f) {
        showDialog(getString(R.string.set_filter_ing));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Bitmap bitmap = BmpUtil.adjust(mImgBitmap, mBrightness, mSaturation, mContrast);
                Bitmap retBitmap = Bitmap.createBitmap(bitmap.copy(
                        Bitmap.Config.ARGB_8888, true));
                PhotoProcessing.filterPhoto(retBitmap, f);
                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap == null) return;
                mRetBitmap = bitmap;
                mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
            }
        });
    }

    private void updateImageViewBitmap() {
        Bitmap preRetBitmap = Bitmap.createBitmap(mImgBitmap.copy(
                Bitmap.Config.ARGB_8888, true));
        PhotoProcessing.filterPhoto(preRetBitmap, oldPosition);
        mRetBitmap = BmpUtil.adjust(preRetBitmap, mBrightness, mSaturation, mContrast);
        if (mRetBitmap != null) {
            mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
            if (preRetBitmap != null && !preRetBitmap.isRecycled() && preRetBitmap != mRetBitmap) {
                preRetBitmap.recycle();
            }
        }
    }

    private float calSeekBarRealValue(SeekBar seekBar, int progress, ColorTuneRange range) {
        int progressRange = seekBar.getMax();
        float value = progress * 1.0f / progressRange * range.getRange() + range.getMin();
        return value;
    }

    private void clearSelection() {
        mDataBinding.llFilter.setVisibility(View.GONE);
        mDataBinding.llMagnify.setVisibility(View.GONE);
        mDataBinding.llMore.setVisibility(View.GONE);
    }

    public void applyCropImage(Bitmap bitmap) {
        showDialog(getString(com.stark.common.res.R.string.handling));
        Config config;
        config = Config.verifyByAppCode(String.valueOf(APPCODE));
        ImgOcrEntry.init(config);
        ImgOcrEntry.getOcrReqManager().urlImages(this, bitmap, new IRetCallback<List<OcrRetBean.Word>>() {
            @Override
            public void onRet(String errCode, String errMsg, @Nullable List<OcrRetBean.Word> wordList) {
                if (wordList == null) {
                    ToastUtils.showShort(errMsg);
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                OcrRetBean.Word word = null;
                for (int i = 0; i < wordList.size(); i++) {
                    word = wordList.get(i);
                    stringBuilder.append(word.getWords());
                    if (i != wordList.size() - 1) {
                        stringBuilder.append("\n");
                    }
                }
                dismissDialog();
                RecResultActivity.sResult = stringBuilder.toString();
                startActivity(RecResultActivity.class);
            }
        });
    }

}